package com.kfyang.manualgear.generator.impl.jdbc.orm;

import com.kfyang.manualgear.constant.Constants;
import com.kfyang.manualgear.generator.impl.jdbc.constant.SqlConstants;
import com.kfyang.manualgear.generator.impl.jdbc.constant.StatementConstants;
import com.kfyang.manualgear.constant.TypeNameConstants;
import com.kfyang.manualgear.struct.EntityInfo;
import com.squareup.javapoet.MethodSpec;

import java.util.ArrayList;
import java.util.List;

public class DeleteMethod extends AbstractMethod {
    protected DeleteMethod(MethodSpec.Builder methodBuilder, EntityInfo entityInfo, boolean forOne) {
        super(methodBuilder, entityInfo, forOne);
    }

    @Override
    protected void prepareSql() {
        StringBuilder sqlBuilder = new StringBuilder(StatementConstants.SQL_DEFINE);
        List<Object> parameters = new ArrayList<>();
        if (entityInfo.deleteInfo == null) { // 直接删除
            parameters.add(entityInfo.tableName);
            parameters.add(entityInfo.idInfo.col);
            if (forOne) {
                sqlBuilder.append(SqlConstants.DELETE_SQL_ONE);
            } else {
                sqlBuilder.append(SqlConstants.DELETE_SQL_MANY);
            }
        } else { // 逻辑删除
            parameters.add(entityInfo.tableName);
            parameters.add(entityInfo.deleteInfo.col);
            sqlBuilder.append(SqlConstants.UPDATE_LOGICAL_DELETE_FLAG);

            if (entityInfo.updateTimeInfo != null) {
                parameters.add(entityInfo.updateTimeInfo.col);
                sqlBuilder.append(" and $L = ?");
            }

            parameters.add(entityInfo.idInfo.col);
            if (forOne) {
                sqlBuilder.append(" where $L = ?");
            } else {
                sqlBuilder.append(" where $L in ");
            }
        }
        if (forOne) { // 删除一条
            sqlBuilder.append(Constants.QUOTA);
        } else { // 删除多条
            sqlBuilder.append(Constants.QUOTA + " + inList(ids.size())");
        }

        methodBuilder.addStatement(sqlBuilder.toString(), parameters.toArray());
    }

    @Override
    public void addReturn() {
        StringBuilder returnBuilder = new StringBuilder("return jdbcTemplate.update(sql");
        List<Object> parameters = new ArrayList<>();
        if (entityInfo.deleteInfo != null && entityInfo.updateTimeInfo != null) { // 逻辑删除需更新 updateTime 字段
            parameters.add(TypeNameConstants.DATE_TYPE);
            returnBuilder.append(", new $T()");
        }

        if (forOne) {
            returnBuilder.append(", id)");
        } else {
            returnBuilder.append(", ids.toArray())");
        }

        methodBuilder.addStatement(returnBuilder.toString(), parameters.toArray());
    }
}
